Is it possible to transpile local modules from nod

2020-07-23 05:35发布

问题:

I have 2 typescript projects which contain few classes. I have added Project1's dependency in the Project2 in package.json

{
  "name": "Project2",
  "dependencies": {
    "@Project1": "file:../Project1/dist"
  }
}

Both the project are built using

"target": "es5", "module": "es2015",

I am using Karma-Webpack for setting up test environment for the projects. To transpile the code I have used babel-loader (with preset: es2015) instead of ts-loader. It transpiles the code from the Project2 but the code from Project1 located in node_modules is not getting transpiled. Due to that it throws below error when the test is run

Chrome 55.0.2883 (Windows 10 0.0.0) ERROR Uncaught SyntaxError: Unexpected token export at spec.bundle.js:80972

I was wondering is it possible to transpile local modules from node_modules using webpack?

Note: if I change the module type to "commonjs", it works but this not the solution I am looking for.

Any suggestions???

回答1:

Well, I faced this error since I am using es2015 to compile the parent module. If you use commonjs, you wont face this issue.

You can transpile the node module code by adding below in webpack configurations in karma.config.file.

webpack: {
            resolve: {
                extensions: ['', '.ts', '.js']
            },

            module: {
                loaders: [
                    {
                        // This will transpile Typescript files
                        test: /\.ts(x?)$/,
                        exclude: /node_modules/,
                        loader: "babel-loader" + "?presets[]=es2015" + "!ts-loader",
                    },
                    {
                        // This will transpile ES2015 javascript files
                        test: /\.js(x?)$/,
                        include: [
                            path.resolve(__dirname, "node_modules/<<YOUR MODULE NAME>>")
                        ],
                        loader: "babel-loader" + "?presets[]=es2015"
                    }
                ]
            }
        },

Now, Webpack will transpile both JS/TS code using babel-loader.